import java.util.*;

/**
 * @author LKQ
 * @date 2022/3/14 11:02
 * @description 滑动窗口，窗口大小为2个篮子
 */
public class Solution2 {
    public static void main(String[] args) {
        Solution2 solution2 = new Solution2();
        int[] fruit = {3,3,3,1,2,1,1,2,3,3,4};
        solution2.totalFruit(fruit);
    }
    public int totalFruit(int[] fruits) {
        int n = fruits.length;
        if (n <= 2) {
            return n;
        }
        int left = 0, right = 0, count = 0;
        int ans = 0;
        // 每种水果出现次数
        int[] cnt = new int[n];
        while (right < n) {
            cnt[fruits[right]]++;
            if (cnt[fruits[right]] == 1) {
                count++;
            }
            while (count > 2) {
                // 篮子中超过两种水果，下面的程序会导致水果数最少的先减少到0，
                cnt[fruits[left]]--;
                if (cnt[fruits[left]] == 0) {
                    count--;
                }
                left++;
            }
            ans = Math.max(ans, right - left + 1);
            right++;
        }
        return ans;
    }
}
